package com.ym.ms.controller;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.login.SsoTokenLoginHelper;
import com.xxl.sso.core.store.SsoLoginStore;
import com.xxl.sso.core.store.SsoSessionIdHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import com.xxl.sso.core.util.JedisUtil;
import com.ym.ms.commons.Confs;
import com.ym.ms.dto.ResultCode;
import com.ym.ms.entity.sys.TSysUser;
import com.ym.ms.mapper.ISystemUserMapper;
import com.ym.ms.service.ISystemUserService;
import com.ym.paas.dto.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.UUID;


/**
 * @author zhang
 */
@Api(tags = "登陆")
@Controller
@RequestMapping("/app")
public class AppLoginController {
    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(AppLoginController.class);

    @Value("${spring.profiles.active}")
    private String active;
    @Value("${xxl.sso.redis.expire.minite}")
    private int redisExpireMinite;

    @Resource
    private ISystemUserMapper sysUserMapper;

    /**
     * doLogin
     *
     * @param username
     * @param password
     * @param sob
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result doLogin(String username,
                          String password,
                          Integer sob) {
        // valid login
        TSysUser usr = sysUserMapper.qryOne(username, sob);
        if (usr == null) {
            LOG.error(ResultCode.BIZ00001.getMessage() + " username:" + username);
            return Result.err(ResultCode.BIZ00001);
        }
//        if (!Md5Util.isMatchPassword(password.trim(), usr.getPassword())) {
//            LOG.error(ResultCode.BIZ00004.getMessage() + " username:" + username);
//            return Result.err(ResultCode.BIZ00004);
//        }
        // 1、make xxl-sso user
        XxlSsoUser xxlUser = new XxlSsoUser();
        xxlUser.setUserid(String.valueOf(usr.getAccount()));
        xxlUser.setUsername(usr.getRealName());
        xxlUser.setVersion(UUID.randomUUID().toString().replaceAll("-", ""));
        xxlUser.setExpireMinite(SsoLoginStore.getRedisExpireMinite());
        xxlUser.setExpireFreshTime(System.currentTimeMillis());

        // 2、make session id
        String sessionId = SsoSessionIdHelper.makeSessionId(xxlUser);
        // 3、login, store storeKey
        SsoTokenLoginHelper.login(sessionId, xxlUser);
        // save user data to redis
        return Result.ok(sessionId);
    }

    /**
     * Logout
     *
     * @param sessionId
     * @return
     */
    @RequestMapping(Conf.SSO_LOGOUT)
    @ResponseBody
    public Result logout(String sessionId) {
        // logout
        SsoTokenLoginHelper.logout(sessionId);
        // del sessionData
        removeStorageData(sessionId);
        return Result.ok();
    }

    private String redisKey(String userName) {
        return Confs.SYSTEM_USER.concat("#").concat(userName);
    }

    private void removeStorageData(String sessionId) {
        String userName = SsoSessionIdHelper.parseStoreKey(sessionId);
        if (userName != null) {
            String redisKey = redisKey(userName);
            JedisUtil.del(redisKey);
        }
    }

}
